package com.pactera.miyuangroup.controller.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pactera.miyuangroup.db.entity.LoginRole;
import com.pactera.miyuangroup.db.entity.LoginUser;
import com.pactera.miyuangroup.db.enums.ShowState;
import com.pactera.miyuangroup.filter.CurrentUser;
import com.pactera.miyuangroup.service.LoginRoleService;
import com.pactera.miyuangroup.vo.convertor.LoginUserConvert;
import com.pactera.miyuangroup.vo.request.web.AddUserRequest;
import com.pactera.miyuangroup.vo.request.web.UpdateUserRequest;
import com.pactera.miyuangroup.vo.response.*;
import com.pactera.miyuangroup.vo.response.web.QueryUserDetailsRes;
import com.pactera.miyuangroup.vo.response.web.UserListRes;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;
import com.pactera.miyuangroup.service.LoginUserService;
import com.pactera.miyuangroup.vo.request.PageRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户信息controller
 *
 * @author 陈浩
 * @ClassName: User
 * @Description:
 * @date 2018年4月17日 上午10:08:14
 */
@Api(description = "用户信息接口")
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private LoginUserService loginUserService;

    @Autowired
    private LoginRoleService loginRoleService;

    @Autowired
    private LoginUserConvert loginUserConvert;

    /**
     * 分页查询用户
     *
     * @param @param  voidRequest
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 上午11:11:07
     */
    @ApiOperation(value = "用户信息列表", notes = "用户信息列表分页查询")
    @RequestMapping(value = "/userList", method = RequestMethod.POST)
    public ResultModel<Page<UserListRes>> getUserList(@RequestBody PageRequest PageRequest) {
        log.info("调用分页查询接口");
        log.info("current = {}", PageRequest.getCurrent(), "size = {}", PageRequest.getSize());
        if (PageRequest.getCurrent() < 0 || PageRequest.getSize() < 1) {
            ResultModel.fail(ResultStatusCode.INVALID_PAGE);
        }
        Page<UserListRes> Page = loginUserService.selectUserList(PageRequest);
        return ResultModel.ok(Page);
    }


    /**
     * 新增用户
     *
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 下午5:01:45
     * @author 陈浩
     */
    @ApiOperation(value = "新增用户", notes = "新增web登录用户")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ResultModel<VoidResponse> addUser(@CurrentUser User user, HttpServletRequest request, @RequestBody AddUserRequest req) {

        boolean val = loginUserService.validateName(req.getUserName());
        if (val) {//用户名已存在
            return ResultModel.fail(ResultStatusCode.USER_NAME_ALREADY_EXISTED);
        }
        boolean flg = loginUserService.AddUserByWeb(request, req, user.getId());
        if (!flg) {
            return ResultModel.fail(ResultStatusCode.ADD_USER_FAILURE);
        }
        return ResultModel.ok();
    }

    /**
     * 查询用户
     *
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 下午5:01:45
     * @author 陈浩
     */
    @ApiOperation(value = "查询用户", notes = "查询web用户信息，用作修改")
    @ApiImplicitParams({@ApiImplicitParam(value = "用户ID", name = "userId", required = true, paramType = "path")})
    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public ResultModel<QueryUserDetailsRes> selectUser(@PathVariable String userId) {

        log.info("查询用户信息，ID：{}", userId);
        QueryUserDetailsRes queryUserDetailsRes = new QueryUserDetailsRes();
        LoginUser user = loginUserService.selectById(userId);
        queryUserDetailsRes = loginUserConvert.convert2QueryUserDetails(user);
        EntityWrapper<LoginRole> ew = new EntityWrapper<LoginRole>();
        ew.eq("login_user_id", userId);
        List<LoginRole> roles = loginRoleService.selectList(ew);
        List<String> rolesId = roles.stream().map(s -> {
            return s.getRoleId();
        }).collect(Collectors.toList());
        queryUserDetailsRes.setRoleId(rolesId);
        return ResultModel.ok(queryUserDetailsRes);
    }


    /**
     * 修改用户
     *
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 下午5:01:45
     * @author 陈浩
     */
    @ApiOperation(value = "修改用户", notes = "修改eb登录用户")
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public ResultModel<VoidResponse> UpdateUser(@CurrentUser User user, HttpServletRequest request, @RequestBody UpdateUserRequest req) {
        boolean flg = loginUserService.UpdateUserByWeb(request, req, user.getId());
        if (!flg) {
            return ResultModel.fail(ResultStatusCode.UPDATE_USER_FAILURE);
        }
        return ResultModel.ok();
    }


    /**
     * 删除用户
     *
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 下午5:01:45
     * @author 陈浩
     */
    @ApiOperation(value = "删除用户", notes = "删除eb登录用户")
    @RequestMapping(value = "/delUser/{userId}", method = RequestMethod.GET)
    public ResultModel<VoidResponse> DelUser(@PathVariable String userId) {
        LoginUser user = loginUserService.selectById(userId);
        if (null == user) {
            return ResultModel.fail(ResultStatusCode.USER_DOES_NOT_EXIST);
        }
        user.setState(ShowState.DELETE);
        user.setModifierTime(new Date());
        boolean flg = loginUserService.updateById(user);
        if (!flg) {
            return ResultModel.fail(ResultStatusCode.DELETE_USER_FAILURE);
        }
        return ResultModel.ok();
    }


    /**
     * 同步用户
     * @return
     */
    @ApiOperation(value = "同步用户", notes = "同步用户")
    @RequestMapping(value = "/syncUserInfo", method = RequestMethod.GET)
    public ResultModel<VoidResponse> syncUserInfo() {
        boolean flg = loginUserService.syncMiyuanUserInfo();
        if (!flg) {
            return ResultModel.warning(ResultStatusCode.DATA_IS_SYNC);
        }
        return ResultModel.ok();
    }


    /**
     * 启用、停用用户
     *
     * @param @return
     * @throws
     * @Description:
     * @date 2018年4月17日 下午5:01:45
     * @author 王武
     */
    @ApiOperation(value = "启用、停用用户", notes = "启用、停用用户")
    @RequestMapping(value = "/enableUser/{userId}", method = RequestMethod.GET)
    public ResultModel<VoidResponse> EnableUser(@CurrentUser User u, @PathVariable String userId) {
        LoginUser user = loginUserService.selectById(userId);
        if (null == user) {
            return ResultModel.fail(ResultStatusCode.USER_DOES_NOT_EXIST);
        }
        if (ShowState.DISABLE.compareTo(user.getState()) == 0) {
            user.setState(ShowState.ENABLE);
        } else {
            user.setState(ShowState.DISABLE);
        }
        user.setModifierTime(new Date());
        user.setModifier(u.getId());
        loginUserService.updateById(user);
        return ResultModel.ok();
    }
}
